package cn.myframe.utils;

import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.IOException;

import static cn.myframe.utils.HdfsUtils.getFileSystem;

/*******************
 *@Describe 持续写实例
 *@author 封神梦
 *@Time 2022/4/20
 *@Company http://com.yiview.com
 ****************/
public class HdfsWriteInstance {

    String spath;
    FileSystem fs = null;
    FSDataOutputStream outputStream = null;
    int off = 0;

    /**
     * 打开创建文件
     * @param path
     * @return
     */
    public boolean openfile(String path) {
        this.spath = path;
        try {
            fs = getFileSystem(path);
            outputStream = fs.create(new Path(path), true);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 写入数据
     * @param data
     * @return
     */
    public boolean writeData(byte[] data) {
        try {
            outputStream.write(data, off, data.length);
            off += data.length;
        } catch (IOException e) {
            e.printStackTrace();
        }


        return false;
    }

    /**
     * 关闭文件
     */
    public void closeFile() {
        try {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
            if (fs != null) {
                fs.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
